<template>
  <!--  当前月份-->
  <view class="schedule-view">
    <view v-if="index === 0">
      <HeaderNavTabarVue
        :iconFont="'icon-jiahao'"
        :iconFont1="'icon-sousuo'"
        :title="'日程'"
        @leftIcon="leftIcon"
        @rightIcon="rightIcon"
        @rightIcon1="rightIcon1"
      />
      <view class="content">
        <ren-calendar
          ref="ren"
          :headerBar="true"
          :markDays="markDays"
          :open="true"
          @onDayClick="onDayClick"
        ></ren-calendar>
      </view>

      <view class="huiyi-box-list">
        <view class="header-box">
          <h4>
            {{ dayjs(curDate).format('MM月DD日') }} 周{{ weekDays[dayjs(curDate).day()] }}
            <text v-if="dayjs(curDate).format('YYYY:MM:DD') === dayjs().format('YYYY:MM:DD')"
              >(今天)
            </text>
            <text
              v-if="
                dayjs(curDate).format('YYYY:MM:DD') ===
                dayjs().subtract(1, 'day').format('YYYY:MM:DD')
              "
            >
              (昨天)
            </text>
            <text
              v-if="
                dayjs(curDate).format('YYYY:MM:DD') === dayjs().add(1, 'day').format('YYYY:MM:DD')
              "
            >
              (明天)
            </text>
          </h4>
          <p>
            <text @tap="optionPerson" v-show="optionPersonArrId.length === 0">选择成员</text>
            <text @tap="closePerson" v-show="optionPersonArrId.length != 0">
              <text v-for="(v, i) in optionPersonArrId" :key="i">
                <text v-show="i < 3">
                  {{ v.nickName }}
                </text>
              </text>
              <text v-show="optionPersonArrId.length > 3">等</text>
              <i class="iconfont icon-cuowuguanbiquxiao"></i>
            </text>
          </p>
        </view>
      </view>
      <ScheduleCard
        v-for="(item, index) in ScheduleCardList"
        :key="index"
        :activeClass="item.activeClass"
        :cardContent="item.describe"
        :cardTitle="item.reason"
        :countPerson="JSON.parse(item.participants).length"
        :scheduleType="item.type"
        @tap="goDefineScheduleView(item)"
      />
    </view>
    <!--  -->

    <!--  待办-->
    <view v-if="index === 1">
      <HeaderNavTabarVue :iconFont="'icon-jiahao'" :title="'待办'" @rightIcon="addTodo" />
      <scroll-view v-if="todoList.length > 0" class="todo-container">
        <view
          v-for="(item, index) in todoList.filter((v) => v.type === 0)"
          :key="item.mattersId"
          class="todo-item-container"
        >
          <radio :checked="item.type === 1" :value="item.type" @tap="handleCheckTodo(item)"></radio>
          <view class="todo-item">
            <view class="title">{{ item.title }}</view>
            <view class="creator">创建者: {{ item.nickName }}</view>
            <view class="participants">
              参与者:
              <view
                v-for="participant in item.participants"
                :key="participant.userId"
                style="display: inline; margin-right: 8rpx"
              >
                {{ participant.nickName }}
              </view>
            </view>
          </view>
        </view>
        <view
          v-if="todoList.filter((v) => v.type === 1).length > 0"
          style="
            display: flex;
            width: 100%;
            justify-content: center;
            height: 80rpx;
            align-items: center;
          "
        >
          <view
            v-if="showCompleted"
            style="display: flex; padding: 10rpx"
            @tap="showCompleted = !showCompleted"
          >
            <text class="show-completed-chip-active"> 隐藏已完成事项</text>
            <uv-icon color="#999" name="arrow-up"></uv-icon>
          </view>
          <view
            v-else
            style="display: flex; padding: 10rpx"
            @tap.stop="showCompleted = !showCompleted"
          >
            <text class="show-completed-chip-inactive"> 显示已完成事项</text>
            <uv-icon color="#999" name="arrow-down"></uv-icon>
          </view>
        </view>
        <view
          v-for="(item, index) in todoList.filter((v) => v.type === 1)"
          v-if="showCompleted"
          :key="item.mattersId"
          class="todo-item-container"
        >
          <radio :checked="item.type === 1" :value="item.type" @tap="handleCheckTodo(item)"></radio>
          <view class="todo-item">
            <view class="title">{{ item.title }}</view>
            <view class="creator">创建者: {{ item.nickName }}</view>
            <view class="participants">
              参与者:
              <view
                v-for="participant in item.participants"
                :key="participant.userId"
                style="display: inline; margin-right: 8rpx"
              >
                {{ participant.nickName }}
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
     <!-- <view
        v-else
        style="
          width: 100%;
          height: calc(100vh - 200rpx);
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <view>暂无待办事项</view>
      </view> -->
			<view class="uv-empty" v-else>
				<uv-empty text="暂无待办事项" icon="../../static/images/empty.png"></uv-empty>
			</view>
    </view>
    <uv-tabbar :value="index" activeColor="#165DFF" @change="tabChange">
      <uv-tabbar-item text="当前月份">
        <template v-slot:inactive-icon>
          <image
            class="icon"
            src="@/static/icon/faqi.svg"
            style="width: 40rpx; height: 40rpx"
          ></image>
        </template>
        <template v-slot:active-icon>
          <image
            class="icon"
            src="@/static/icon/faqi-active.svg"
            style="width: 40rpx; height: 40rpx"
          ></image>
        </template>
      </uv-tabbar-item>
      <uv-tabbar-item text="待办">
        <template v-slot:inactive-icon>
          <image
            class="icon"
            src="@/static/icon/stamp.svg"
            style="width: 40rpx; height: 40rpx"
          ></image>
        </template>
        <template v-slot:active-icon>
          <image
            class="icon"
            src="@/static/icon/stamp-active.svg"
            style="width: 40rpx; height: 40rpx"
          ></image>
        </template>
      </uv-tabbar-item>
    </uv-tabbar>
  </view>
</template>

<script setup>
import HeaderNavTabarVue from '@/components/HeaderNavTabar/HeaderNavTabar.vue'
import ScheduleCard from './module/ScheduleCard.vue'
import { defineProps, ref } from 'vue'
import { onReady, onShow, onLoad } from '@dcloudio/uni-app'
import optionDeptPerson from '@/store/modules/optionDeptPerson'
import { getScheduleRecord } from '@/api/schedule'
import dayjs from 'dayjs'

const userIdArr = ref([])
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
import { editAgentMatterType, getAgentMatterList } from '@/api/schedule'
import { getUserProfile } from '@/api/system/user'

const currentMontyTitle = dayjs().format('YYYY年MM月')
const props = defineProps({
  title: {
    type: String,
    default: '',
    required: true,
  },
})

const index = ref(0)

const ScheduleCardList = ref([])
// 选择成员
const optionPerson = () => {
  uni.navigateTo({
    url: '/components/OptionDeptPerson/index?type=person',
  })
}
const closePerson = async () => {
  optionDeptPerson.mutations.clearOptionPerson(optionDeptPerson.state)
  optionPersonArrId.value = []
  await getScheduleRecordFn(
    dayjs(curDate.value).format('YYYY:MM:DD 00:00:00'),
    dayjs(curDate.value).format('YYYY:MM:DD 23:59:59'),
    userIdArr.value,
  )
}
const optionPersonArrId = ref([])
onShow(async () => {
  if (optionDeptPerson.state.optionPerson) {
    optionPersonArrId.value = optionDeptPerson.state.optionPerson.map((v) => {
      return {
        userId: v.userId,
        nickName: v.nickName,
      }
    })
    // let userIds =  optionPersonArrId.value.map(v=>v.userId)
    //  await getScheduleRecordAllFn(userIds)
  }
  getAgentMatterList().then((res) => {
    if (res.code === 200) {
      const data = res.rows
      todoList.value = data.map((v) => {
        return {
          mattersId: v.mattersId,
          title: v.title,
          nickName: v.nickName,
          participants: JSON.parse(v.participants),
          type: v.type,
        }
      })
    }
  })
	
	await getScheduleRecordFn(
	  dayjs(curDate.value).format('YYYY-MM-DD 00:00:00'),
	  dayjs(curDate.value).format('YYYY-MM-DD 23:59:59'),
	  userIdArr.value,
	)
})
const leftIcon = () => {
  optionDeptPerson.mutations.clearOptionPerson(optionDeptPerson.state)
}
const tabChange = async (e) => {
  index.value = e
  if (index.value === 0) {
    await getScheduleRecordFn(
      dayjs().format('YYYY:MM:DD 00:00:00'),
      dayjs().format('YYYY:MM:DD 23:59:59'),
      optionPersonArrId.value.map((v) => v.userId),
    )
  }
}
// 新建日程
const rightIcon = () => {
  uni.navigateTo({
    url: '/pages/schedule/components/addSchedule',
  })
}
// 搜索
const rightIcon1 = () => {
  uni.navigateTo({
    url:
      '/pages/schedule/components/searchSchedule?personIdArr=' +
      optionPersonArrId.value.map((v) => v.userId),
  })
}

const addTodo = () => {
  optionDeptPerson.mutations.clearOptionPerson(optionDeptPerson.state)
  uni.navigateTo({
    url: '/pages/schedule/addTodo',
  })
}

const curDate = ref(dayjs())
const goDefineScheduleView = (item) => {
  uni.navigateTo({
    url:
      '/pages/schedule/components/defineSchduleRecord?item=' +
      encodeURIComponent(JSON.stringify(item)),
  })
}
// 标记的集合
const markDays = ref(['2025-01-11', '2025-01-09', '2025-01-17', '2025-01-19'])

const ren = ref(null)
onReady(() => {
  curDate.value = ren.value.getToday().date
})
// 点击的日期
const onDayClick = async (data) => {
  curDate.value = data.date
  await getScheduleRecordFn(
    dayjs(curDate.value).format('YYYY-MM-DD 00:00:00'),
    dayjs(curDate.value).format('YYYY-MM-DD 23:59:59'),
    optionPersonArrId.value.length !== 0
      ? optionPersonArrId.value.map((v) => v.userId)
      : userIdArr.value,
  )
}

// 待办列表
const todoList = ref([])

const handleCheckTodo = (item) => {
  // todoList.value = todoList.value.map((v) => {
  //   if (v.mattersId === mattersId) {
  //     v.type = v.type === 0 ? 1 : 0
  //   }
  //   return v
  // })
  editAgentMatterType({
    mattersId: item.mattersId,
    type: item.type === 0 ? 1 : 0,
  }).then((res) => {
    if (res.code === 200) {
      getAgentMatterList().then((res) => {
        if (res.code === 200) {
          const data = res.rows
          todoList.value = data.map((v) => {
            return {
              mattersId: v.mattersId,
              title: v.title,
              nickName: v.nickName,
              participants: JSON.parse(v.participants),
              type: v.type,
            }
          })
        }
      })
    }
  })
}

const showCompleted = ref(false)
// 获取标记点
const getScheduleRecordAllFn = async (userIds) => {
  let params = {
    timeLte: dayjs(curDate.value).startOf('month').format('YYYY-MM-DD 00:00:00'),
    timeGte: dayjs(curDate.value).endOf('month').format('YYYY-MM-DD 23:59:59'),
    userIds: userIds,
  }
  let { rows } = await getScheduleRecord(params)
  markDays.value = rows.map((v) => {
    return dayjs(v.startTime).format('YYYY-MM-DD')
  })
}
// 获取日程
const getScheduleRecordFn = async (
  timeLte = dayjs(curDate.value).format('YYYY-MM-DD 00:00:00'),
  timeGte = dayjs(curDate.value).format('YYYY-MM-DD 23:59:59'),
  userIds,
) => {
  let params = {
    timeLte: timeLte,
    timeGte: timeGte,
    userIds: userIds,
  }
  let { rows } = await getScheduleRecord(params)
  ScheduleCardList.value = rows

  await getScheduleRecordAllFn(userIdArr.value)
}

onLoad(async () => {
  userIdArr.value = await getUserProfile().then((res) => [res.data.userId])

})
</script>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

.schedule-view {
  .huiyi-box-list {
    padding: 32rpx;

    .header-box {
      @include flex(center, space-between);

      h4 {
        color: #000000;
        text-align: center;
        font-size: 30rpx;
        font-style: normal;
        font-weight: 500;
      }

      p {
        text {
          color: #165dff;
          font-size: 28rpx;
          font-style: normal;
          font-weight: 400;
        }
      }
    }
  }
}

.todo-container {
  //padding: 20rpx;

  .todo-item-container {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
    padding: 20rpx;
    border-bottom: 2rpx solid #f0f0f0;
  }

  .show-completed-chip-inactive {
    //color: #165dff;
		color: #999;
    font-style: normal;
    font-weight: 400;
		margin-right: 10rpx;
  }

  .show-completed-chip-active {
    // color: #165dff;
		margin-right: 10rpx;
		color: #999;
    font-size: 28rpx;
    font-style: normal;
    font-weight: 400;
  }

  .todo-item {
    display: flex;
    flex-grow: 1;
    margin-left: 20rpx;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-start;

    background-color: #ffffff;

    .title {
      font-size: 32rpx;
      color: #333;
    }

    .creator {
      font-size: 28rpx;
      color: #999;
    }

    .participants {
      font-size: 28rpx;
      color: #999;
    }
  }
}
</style>
